package com.kxmall.web.controller.rider;

import cn.dev33.satoken.annotation.SaIgnore;
import com.kxmall.common.core.controller.BaseRiderController;
import com.kxmall.common.core.domain.R;
import com.kxmall.common.utils.IpUtil;
import com.kxmall.rider.domain.KxRider;
import com.kxmall.rider.domain.bo.KxRiderBo;
import com.kxmall.rider.domain.vo.KxRiderVo;
import com.kxmall.rider.domain.vo.RiderLoginDTO;
import com.kxmall.rider.domain.vo.RiderWxDTO;
import com.kxmall.user.domain.vo.KxUserVo;
import com.kxmall.web.controller.rider.service.RiderWxLoginService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author kaixin
 * @version 1.0
 * @date 2023/9/23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/rider/wxLogin")
    public class RiderWxLoginController extends BaseRiderController {

    private final RiderWxLoginService riderWxLoginService;


    /**
     * 微信小程序
     *
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/wechatLogin")
    public R<KxRiderVo> wechatLogin(@RequestBody RiderWxDTO riderWxDTO) {
        KxRiderVo kxRiderVo = riderWxLoginService.wechatLogin(IpUtil.getLocalIP(), riderWxDTO);
        return R.ok(kxRiderVo);

    }

    /**
     * 小程序授权登录
     *
     * @param code 小程序code
     * @return 结果
     */
    @SaIgnore
    @GetMapping("/miniPhoneLogin")
    public R<KxRiderVo> miniPhoneLogin(String code, String encryptedData, String iv) throws WxErrorException {
        return R.ok(riderWxLoginService.miniPhoneLogin(code,encryptedData,iv));
    }

    /**
     * 通过token获取用户信息
     *
     * @return 结果
     */
    @GetMapping("/getRiderInfo")
    public R<RiderLoginDTO> getRiderInfo() {
        Long riderId = getRiderLoginUser().getUserId();
        RiderLoginDTO info = riderWxLoginService.getRiderInfo(riderId);
        return R.ok(info);

    }

    /**
     * 通过token更新用户信息
     *
     * @return 结果
     */
    @GetMapping("/updateRiderInfo")
    public R<RiderLoginDTO> updateRiderInfo(KxRiderBo bo) {
        Long riderId = getRiderLoginUser().getUserId();

        KxRider update = new KxRider();
        update.setId(riderId);
        update.setBirthday(bo.getBirthday());
        update.setAvatarUrl(bo.getAvatarUrl());
        update.setName(bo.getName());
        update.setSex(bo.getSex());
        riderWxLoginService.updateById(update);

        RiderLoginDTO info = riderWxLoginService.getRiderInfo(riderId);
        return R.ok(info);

    }


    /**
     * 解密获取手机号
     *
     * @return 结果
     */
    @SaIgnore
    @GetMapping("/decryptS5")
    public R<String> decryptS5(String ip, String raw) {
        return R.ok("操作成功！",riderWxLoginService.decryptS5(ip, raw));
    }
}
